import 'package:flutter/material.dart';
import 'package:hi_net/navigator/hi_navigator.dart';
import 'package:hi_net/page/favorite_page.dart';
import 'package:hi_net/page/home_page.dart';
import 'package:hi_net/page/mine_page.dart';
import 'package:hi_net/page/ranking_page.dart';
import 'package:hi_net/util/color.dart';

///主页面 + 底部导航
class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  final _defaultColor = Colors.grey;
  final _activeColor = primary;
  int _currentIndex = 0;
  static int initialPage = 0;
  final PageController _controller = PageController(initialPage: initialPage);
  late List<Widget> _pages;
  bool _hasBuild = false;

  @override
  Widget build(BuildContext context) {
    _pages = [
      HomePage(onJumpTo: (index) => _onJumpTo(index, pageChange: false)),
      RankingPage(),
      FavoritePage(),
      MinePage()
    ];
    if (!_hasBuild) {
      //页面第一次打开时通知打开的是那个tab
      HiNavigator.getInstance.onBottomTabChange(initialPage, _pages[initialPage]);
      _hasBuild = true;
    }
    return Scaffold(
      body: PageView(
        controller: _controller,
        onPageChanged: (index) => _onJumpTo(index, pageChange: true),
        // 设置pageView不可滑动
        physics: const NeverScrollableScrollPhysics(),
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        selectedItemColor: _activeColor,
        type: BottomNavigationBarType.fixed,
        onTap: (index) => _onJumpTo(index),
        items: [
          _bottomItem("首页", Icons.home, 0),
          _bottomItem("排行", Icons.local_fire_department, 1),
          _bottomItem("收藏", Icons.favorite, 2),
          _bottomItem("我的", Icons.live_tv, 3),
        ],
      ),
    );
  }

  _bottomItem(String title, IconData icon, int index) {
    return BottomNavigationBarItem(
      icon: Icon(icon, color: _defaultColor),
      activeIcon: Icon(icon, color: _activeColor),
      label: title,
    );
  }

  void _onJumpTo(int index, {pageChange = false}) {
    if (!pageChange) {
      //bottom关联PageView展示对应tab
      _controller.jumpToPage(index);
    } else {
      HiNavigator.getInstance.onBottomTabChange(index, _pages[index]);
    }

    setState(() {
      //更新当前选中的tab
      _currentIndex = index;
    });
  }
}
